package com.cyru.statemachine.core.impl;

import com.cyru.statemachine.core.Action;
import com.cyru.statemachine.core.Condition;
import com.cyru.statemachine.core.Trigger;

import java.util.Objects;

/**
 * description:
 *
 * @author zhangxuchuan
 * date 2022/5/2
 */
public class DefaultTrigger<S, E, C> implements Trigger<S, E, C> {

    private E event;

    private Condition<C> condition;

    private Action<S, E, C> action;

    @Override
    public void setEvent(E event) {
        this.event = event;
    }

    @Override
    public E getEvent() {
        return event;
    }

    @Override
    public void setCondition(Condition<C> condition) {
        this.condition = condition;
    }

    @Override
    public Condition<C> getCondition() {
        return condition;
    }

    @Override
    public void setAction(Action<S, E, C> action) {
        this.action = action;
    }

    @Override
    public Action<S, E, C> getAction() {
        return action;
    }

    @Override
    public boolean check(C context) {
        if (context == null) {
            return true;
        }
        return condition.check(context);
    }

    @Override
    public void execute(S source, S target, E event, C context) {
        if (action != null) {
            action.execute(source, target, event, context);
        }
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(event);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        DefaultTrigger<?, ?, ?> that = (DefaultTrigger<?, ?, ?>) obj;
        return Objects.equals(that.event, obj);
    }
}
